<template>
  <view class="content">
    <view class="zjsc">
      行驶证
    </view>
    <view class="ghmsc">
      <view class="sctp" @click="selectDrvingLicenceFace">
        <view class="img-box">
          <image class="cover-img" :src="imagesVehicleFace[0]" mode="aspectFill"></image>
          <view class="img-text">正面</view>
        </view>
      </view>
      <view class="sctp" @click="selectDrvingLicenceBack">
        <view class="img-box">
          <image class="cover-img" :src="imagesVehicleBack[0]" mode="aspectFill"></image>
          <view class="img-text">背面</view>
        </view>
      </view>
    </view>

    <view class="qrsf">
      <view class="sjxx">
        <view class="uni-form-item">
          <text class="title">*车牌号</text>
          <input class="uni-input" v-model="vehicleData.vehicleNo" :disabled="mtype == 'update'" />
        </view>
        <view class="uni-form-item">
          <text class="title">车辆识别码</text>
          <input :disabled="isIdentifiedFlag" class="uni-input" v-model="vehicleData.vin" />
        </view>
        <view class="uni-form-item">
          <text class="title">车辆类型</text>
          <input :disabled="isIdentifiedFlag" class="uni-input" v-model="vehicleData.vehicleType" />
        </view>
      </view>
    </view>

    <view class="zysx">
      <view class="title">注意事项：</view>
      <view class="list">1、所有上传照片需清晰且未遮挡，四角完整、亮度均匀，请勿进行美化和修改；</view>
    </view>
    <view class="btn" v-if="mtype == 'update'">
      <button type="default" @click.native="openScDialog">解绑</button>
      <button type="primary" v-if="!isIdentifiedFlag" @click.native="handleSubmit">提交</button>
    </view>
    <view v-else class="btn1">
      <button type="primary" v-if="!isIdentifiedFlag" @click.native="handleAddSubmit">提交</button>
    </view>
    <view class="btn1" v-if="isIdentifiedFlag">
      <button type="default" @click.native="openScDialog">解绑</button>
    </view>
    <!-- shanchu -->
    <uni-popup ref="scDialog" type="dialog">
      <uni-popup-dialog type="message" cancelText="取消" confirmText="确定" title="解绑" content="确定解绑此车辆信息？"
        @confirm="dialogConfirmSc" @close="dialogClose"></uni-popup-dialog>
    </uni-popup>
  </view>
</template>
<script>
  import {
    getVehicleDetail,
    getVehicleDict,
    updateVehicle,
    addVehicle,
    getVehicleRecognize,
    deleteVehicle
  } from '@/api/me.js';
  import {
    getAccessToken
  } from '@/utils/auth';
  import config from '@/config'
  import {
    toast
  } from '@/utils/common';
  export default {
    data() {
      return {
        mtype: '',
        isIdentifiedFlag: false,
        imgLoading: false,
        vid: '',
        vehicleDict: [],
        imgFace: false,
        imgBack: false,
        imagesVehicleFace: [config.baseImgUrl + '/driver-licenseFace1.png'],
        imagesVehicleBack: [config.baseImgUrl + '/driver-licenseBack.png'],
        imagesVehicleFaceFlag: true,
        imagesVehicleBackFlag: true,
        vehicleTypeName: '',
        vehicleData: {
          vehicleNo: '',
          vehicleType: '',
          possessor: '',
          functions: '',
          vin: '',
          totalQuality: '',
          ratedLoad: '',
          unladenMass: '',
          registrationDate: null,
          issueDate: null,
          vehicleFaceUrl: '',
          vehicleBackUrl: '',
          id: null,
          isIdentified: false
        },
        errorMsgFac: '',
        errorMsgBac: '',
        imageStyles: {
          width: 180,
          height: 110
        },
        ysjhData: {} // 从接单而来的参数
      };
    },
    onLoad(option) {
      this.getVehivleDict(option.id)
    },
    methods: {
      // 移出图片函数
      async deletephotoFace() {
        let that = this
        that.imagesVehicleFace = []
        that.imagesVehicleFace.push({
          url: config.baseImgUrl + '/driver-licenseFace.png',
          extname: '',
          name: ''
        })
      },
      // 移出图片函数
      async deletephotoBack() {
        let that = this
        that.imagesVehicleBack = []
        that.imagesVehicleBack.push({
          url: config.baseImgUrl + '/driver-licenseBack.png',
          extname: '',
          name: ''
        })
      },
      async getVehivleDict(id) {
        let res = await getVehicleDict()
        if (res.code == 0) {
          this.vehicleDict = res.data.filter(item => item.dictType == 'vehicle_type')
          console.log('this.vehicleDict:', this.vehicleDict)
          if (id) {
            this.mtype = 'update';
            this.vid = id;
            console.log(this.vid, 'vid~~');
            this.getData();
            wx.setNavigationBarTitle({
              title: '修改车辆'
            })

          } else {
            this.mtype = 'add';
            wx.setNavigationBarTitle({
              title: '新增车辆'
            })
          }
        }

      },
      selectDrvingLicenceFace(e) {
        let that = this
        if (that.isIdentifiedFlag) return
        that.imgFace = true
        that.imagesVehicleFace = []
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //从相册选择
          mediaType: ['image'],
          success: function (res) {
            let curSize = res.tempFiles[0].size
            let quelityVal = 100
            let initnum = 0.3 * 1024 * 1024
            if (curSize > initnum) {
              quelityVal = 100 / (curSize / initnum)
            }
            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                that.imagesVehicleFace.push(resp.tempFilePath)
                that.uploadFilesId(resp.tempFilePath, 1);
              },
              fail: (error) => { },
            })
          },
          fail(e) {
            that.imgFace = false
            console.log('上传身份证正面的照片fail：', e)
          }
        });
      },
      uploadFilesId(filepath, type) {
        wx.showLoading({
          title: '正在上传中...',
        });
        let that = this
        uni.uploadFile({
          url: config.baseUrl + '/infra/file/upload',
          filePath: filepath,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data",
            'Authorization': 'Bearer ' + getAccessToken(),
          },
          async success(res) {
            console.log("上传图片后的成功返回");
            console.log(JSON.parse(res.data));
            if (type == 1) {
              that.vehicleData.vehicleFaceUrl = JSON.parse(res.data).data;
            } else that.vehicleData.vehicleBackUrl = JSON.parse(res.data).data;
            let res1 = await getVehicleRecognize(JSON.parse(res.data).data);
            let msg = '',
              iconFlag = ''
            if (res1.code == 0) {
              if (type == 1) {
                if (!res1.data.face) {
                  that.errorMsgFac = '请上传行驶证正面'
                  toast(that.errorMsgFac);
                  return
                } else {
                  that.imgFace = true
                  if (that.mtype != 'add') {
                    if (that.vehicleData.vehicleNo != res1.data.face.data
                      .licenseplatenumber) {
                      that.imgFace = false
                      that.errorMsgFac = '识别车牌号和已有车牌号不一致'
                      toast('识别车牌号和已有车牌号不一致');
                      return
                    }
                  }
                  that.vehicleData.vehicleNo = (!!res1.data.face && res1.data.face.data
                    .licenseplatenumber) || '';
                  that.vehicleData.vin = (!!res1.data.face && res1.data.face.data.vincode) ||
                    '';
                  that.vehicleData.vehicleType = (!!res1.data.face && res1.data.face.data
                    .vehicletype) || '';
                }
              } else {
                if (!res1.data.back) {
                  that.errorMsgFac = '请上传行驶证背面'
                  toast(that.errorMsgFac);
                  return
                } else {
                  that.imgBack = true
                }
              }
              msg = '上传成功'
              iconFlag = 'success'
            } else {
              msg = res1.msg
              iconFlag = 'none'

              if (type == 1) {
                that.imgFace = false
                that.errorMsgFac = res1.msg
              } else {
                that.errorMsgBac = res1.msg
                that.imgBack = false
              }
            }
            wx.hideLoading()
            uni.showToast({
              title: msg,
              icon: iconFlag
            });
          },
          fail(err) {
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            });
            that.errorMsgFac = res1.msg
            if (type == 1) {
              that.imgFace = false
            } else {
              that.imgBack = false
            }
          },
          complete() {
            that.imgLoading = false
            uni.hideLoading();
          }
        })
      },
      selectDrvingLicenceBack(e) {
        let that = this
        if (that.isIdentifiedFlag) return
        that.imgBack = true
        that.imagesVehicleBack = []
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //从相册选择
          mediaType: ['image'],
          success: function (res) {
            let curSize = res.tempFiles[0].size
            let quelityVal = 100
            let initnum = 0.3 * 1024 * 1024
            if (curSize > initnum) {
              quelityVal = 100 / (curSize / initnum)
            }
            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                that.imagesVehicleBack.push(resp.tempFilePath)
                that.uploadFilesId(resp.tempFilePath, 2);
              },
              fail: (error) => { },
            })
          },
          fail(e) {
            that.imgBack = false
            console.log('上传身份证正面的照片fail：', e)
          }
        });
      },
      dialogConfirmSc() {
        wx.showLoading({
          title: '正在解绑中...',
        })
        this.deleteCar();
      },
      dialogClose() {
        this.$refs['scDialog'].close();
        console.log('点击关闭');
      },
      // 删除车辆
      openScDialog() {
        if (this.imgLoading) return
        this.$refs['scDialog'].open();
      },
      async deleteCar() {
        //          if(!this.imgFace){
        //          	uni.showToast({
        //          		title: this.errorMsgFac,
        // 		icon: 'none'
        //          	});
        //          	return
        //          }
        // if(!this.imgBack){
        // 	uni.showToast({
        // 		title: this.errorMsgBac,
        // 		icon: 'none'
        // 	});
        // 	return
        // }
        try {
          let res = await deleteVehicle(this.vid);
          console.log('deleteVehicle: ', res);
          if (res.code == 0) {
            console.log('deleteVehicle: ', res);
            uni.showToast({
              title: `删除成功`
            });
            uni.navigateBack({
              delta: 1
            })
          } else {
            toast(res.msg)
          }
          wx.hideLoading()
        } catch (e) {
          return false;
        }
      },
      //获取车辆详情
      async getData() {
        try {
          let res = await getVehicleDetail(this.vid);
          console.log('getVehicleDetail: ', res);
          if (res.code == 0) {
            this.isIdentifiedFlag = res.data.isIdentified
            this.vehicleData = res.data;
            this.vehicleData.id = this.vid;
            // let vehicleTypeName = this.vehicleDict.filter((item)=> Number(item.value) == res.data.vehicleType)
            // console.log(vehicleTypeName,'vehicleTypeName==')
            // this.vehicleTypeName = vehicleTypeName[0].label
            this.vehicleData.vehicleType = res.data.vehicleType;
            this.vehicleData.vehicleFaceUrl = res.data.vehicleFaceUrl;
            this.vehicleData.vehicleBackUrl = res.data.vehicleBackUrl;
            if (!!res.data.vehicleFaceUrl) {
              this.imgFace = true
              this.imagesVehicleFace = []
              this.imagesVehicleFace.push(this.vehicleData.vehicleFaceUrl)
            }
            if (!!res.data.vehicleBackUrl) {
              this.imgBack = true
              this.imagesVehicleBack = []
              this.imagesVehicleBack.push(this.vehicleData.vehicleBackUrl)
            }
          }
        } catch (e) {
          return false;
        }
      },
      //新增
      async handleAddSubmit() {
        wx.showLoading({
          title: '正在提交...',
        });
        // if(uni.getStorageSync('isSetSjxx') == 'net'){
        // 	this.$tab.reLaunch('/pages/receivingNet');
        // }else if(uni.getStorageSync('isSetSjxx') == 'jiyun'){
        // 	this.$tab.reLaunch('/pages/receivingJY');
        // }else if(uni.getStorageSync('isSetSjxx') == 'jil'){
        // 	this.$tab.reLaunch('/pages/receiving');
        // }else{}
        return
        if (!this.vehicleData.vehicleNo) {
          uni.showToast({
            title: `请填写车牌号`,
            icon: 'none'
          });
          return
        }
        let data = this.vehicleData
        if (this.imgFace && this.imgBack) {
          data.isIdentified = true
        }
        try {
          let res = await addVehicle(data);
          console.log('addVehicle: ', res);
          if (res.code == 0) {
            console.log('addVehicle: ', res);
            uni.showToast({
              title: `新增成功`
            });
            if (uni.getStorageSync('isSetSjxx')) {
              if (uni.getStorageSync('isSetSjxx') == 'net') {
                this.$tab.reLaunch('/pages/receivingNet');
              } else if (uni.getStorageSync('isSetSjxx') == 'jiyun') {
                this.$tab.reLaunch('/pages/receivingJY');
              } else if (uni.getStorageSync('isSetSjxx') == 'jil') {
                this.$tab.reLaunch('/pages/receiving');
              } else { }
            } else {
              uni.navigateBack({
                delta: 1
              })
            }
          }
          wx.hideLoading()
        } catch (e) {
          return false;
        }
      },
      // 提交信息-编辑
      async handleSubmit() {
        if (this.vehicleData.isIdentified) {
          uni.showToast({
            title: '已认证车辆不能编辑',
            icon: 'none'
          });
          return
        }
        wx.showLoading({
          title: '正在提交...',
        });

        if (this.imgLoading) return
        this.ysjhData = uni.getStorageSync('ysjhData');
        //校验参数
        // if(!this.imgFace){
        // 	uni.showToast({
        // 		title: this.errorMsgFac,
        // 		icon: 'none'
        // 	});
        // 	return
        // }
        // if(!this.imgBack){
        // 	uni.showToast({
        // 		title: this.errorMsgBac,
        // 		icon: 'none'
        // 	});
        // 	return
        // }
        if (!this.vehicleData.vehicleNo) {
          uni.showToast({
            title: `请填写车牌号`,
            icon: 'none'
          });
          return
        }
        if (this.imgFace && this.imgBack) {
          this.vehicleData.isIdentified = true
        }
        let data = this.vehicleData;
        try {
          let res = await updateVehicle(data);
          console.log('updateVehicle: ', res);
          if (res.code == 0) {
            console.log('updateVehicle: ', res);
            uni.showToast({
              title: `更新成功`
            });
            if (uni.getStorageSync('isSetSjxx')) {
              console.log('这里是有运单数据缓存的，所以跳转回接单页面')
              this.$tab.reLaunch('/pages/index');
            } else {
              this.$tab.reLaunch('/packageB/pages/mine/vehicle/vehicle');
            }
          }
          wx.hideLoading()
        } catch (e) {
          return false;
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .content {
    font-size: 15px;
    padding: 20rpx;
    height: 100vh;
    position: relative;

    .btn,
    .btn1 {
      position: fixed;
      display: flex;
      bottom: 10px;
      width: 95%;

      button:first-child {
        margin: 0 10rpx 0 0;
      }

      button {
        width: 49%;
        background-color: #409EFE;
        font-size: 30rpx;
        margin: 0;
        color: #fff;
      }
    }

    .btn1 {
      button {
        width: 100% !important;
      }
    }
  }
</style>